#!/bin/bash

# OTA后端Docker构建和部署脚本
# 使用方法: ./build.sh [build|start|stop|restart|logs|clean] [选项]

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# 日志函数
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

log_debug() {
    echo -e "${BLUE}[DEBUG]${NC} $1"
}

# 显示帮助信息
show_help() {
    echo "OTA后端Docker构建和部署脚本"
    echo ""
    echo "使用方法:"
    echo "  $0 build [选项]     - 构建Docker镜像"
    echo "  $0 start [选项]     - 启动服务"
    echo "  $0 stop [选项]      - 停止服务"
    echo "  $0 restart [选项]   - 重启服务"
    echo "  $0 logs [选项]      - 查看日志"
    echo "  $0 clean [选项]     - 清理资源"
    echo "  $0 init             - 初始化数据库"
    echo ""
    echo "选项:"
    echo "  --mysql            使用MySQL数据库"
    echo "  --sqlite           使用SQLite数据库（默认）"
    echo "  --no-cache         构建时不使用缓存"
    echo "  --pull             构建前拉取最新基础镜像"
    echo "  --dev              开发模式，使用本地挂载"
    echo "  --prod             生产模式，使用Docker卷"
    echo "  --follow, -f       查看日志时跟随输出"
    echo "  --help             显示此帮助信息"
    echo ""
    echo "示例:"
    echo "  $0 build --no-cache"
    echo "  $0 start --mysql"
    echo "  $0 logs --follow"
    echo "  $0 clean --all"
}

# 检查Docker是否安装
check_docker() {
    if ! command -v docker &> /dev/null; then
        log_error "Docker未安装，请先安装Docker"
        exit 1
    fi
    
    if ! command -v docker-compose &> /dev/null; then
        log_error "Docker Compose未安装，请先安装Docker Compose"
        exit 1
    fi
}

# 构建镜像
build_image() {
    local build_args=""
    local tag="ota-backend:latest"
    
    if [ "$USE_SQLITE" = true ]; then
        tag="ota-backend:sqlite"
    fi
    
    if [ "$NO_CACHE" = true ]; then
        build_args="$build_args --no-cache"
    fi
    
    if [ "$PULL_LATEST" = true ]; then
        build_args="$build_args --pull"
    fi
    
    log_info "开始构建Docker镜像: $tag"
    docker build $build_args -t $tag .
    
    log_info "镜像构建完成！"
    docker images | grep ota-backend
}

# 启动服务
start_services() {
    local compose_file="docker-compose.yml"
    local compose_args=""
    
    if [ "$USE_SQLITE" = true ]; then
        compose_file="docker-compose.sqlite.yml"
        log_info "使用SQLite模式启动服务"
    else
        log_info "使用MySQL模式启动服务"
    fi
    
    if [ "$DEV_MODE" = true ]; then
        compose_args="$compose_args --profile dev"
        log_info "开发模式启动"
    fi
    
    log_info "启动OTA服务..."
    docker-compose -f $compose_file up -d $compose_args
    
    log_info "服务启动完成！"
    docker-compose -f $compose_file ps
}

# 停止服务
stop_services() {
    local compose_file="docker-compose.yml"
    
    if [ "$USE_SQLITE" = true ]; then
        compose_file="docker-compose.sqlite.yml"
    fi
    
    log_info "停止OTA服务..."
    docker-compose -f $compose_file down
    
    log_info "服务停止完成！"
}

# 重启服务
restart_services() {
    stop_services
    sleep 2
    start_services
}

# 查看日志
show_logs() {
    local compose_file="docker-compose.yml"
    local log_args=""
    
    if [ "$USE_SQLITE" = true ]; then
        compose_file="docker-compose.sqlite.yml"
    fi
    
    if [ "$FOLLOW_LOGS" = true ]; then
        log_args="$log_args -f"
    fi
    
    log_info "查看服务日志..."
    docker-compose -f $compose_file logs $log_args
}

# 初始化数据库
init_database() {
    local container_name="ota-backend"
    
    if [ "$USE_SQLITE" = true ]; then
        container_name="ota-backend-sqlite"
        log_info "初始化SQLite数据库..."
        docker exec $container_name /app/script/setup_database.sh sqlite
    else
        log_info "初始化MySQL数据库..."
        # 等待MySQL启动
        log_info "等待MySQL服务启动..."
        sleep 10
        docker exec $container_name /app/script/setup_database.sh mysql -h mysql -u root -p admin123
    fi
    
    log_info "数据库初始化完成！"
}

# 清理资源
clean_resources() {
    local clean_all=false
    
    if [ "$1" = "--all" ]; then
        clean_all=true
    fi
    
    log_info "清理Docker资源..."
    
    # 停止并删除容器
    docker-compose -f docker-compose.yml down 2>/dev/null || true
    docker-compose -f docker-compose.sqlite.yml down 2>/dev/null || true
    
    # 删除镜像
    docker rmi ota-backend:latest 2>/dev/null || true
    docker rmi ota-backend:sqlite 2>/dev/null || true
    
    if [ "$clean_all" = true ]; then
        log_warn "清理所有相关数据..."
        # 删除数据卷
        docker volume rm ota-backend_ota-data 2>/dev/null || true
        docker volume rm ota-backend_ota-files 2>/dev/null || true
        docker volume rm ota-backend_ota-logs 2>/dev/null || true
        docker volume rm ota-backend_mysql-data 2>/dev/null || true
        
        # 清理未使用的资源
        docker system prune -f
    fi
    
    log_info "清理完成！"
}

# 主函数
main() {
    if [ $# -eq 0 ]; then
        show_help
        exit 1
    fi
    
    local command=$1
    shift
    
    # 默认参数
    USE_SQLITE=true
    NO_CACHE=false
    PULL_LATEST=false
    DEV_MODE=false
    FOLLOW_LOGS=false
    
    # 解析参数
    while [[ $# -gt 0 ]]; do
        case $1 in
            --mysql)
                USE_SQLITE=false
                shift
                ;;
            --sqlite)
                USE_SQLITE=true
                shift
                ;;
            --no-cache)
                NO_CACHE=true
                shift
                ;;
            --pull)
                PULL_LATEST=true
                shift
                ;;
            --dev)
                DEV_MODE=true
                shift
                ;;
            --prod)
                DEV_MODE=false
                shift
                ;;
            --follow|-f)
                FOLLOW_LOGS=true
                shift
                ;;
            --help)
                show_help
                exit 0
                ;;
            --all)
                # 用于clean命令
                shift
                ;;
            *)
                log_error "未知参数: $1"
                show_help
                exit 1
                ;;
        esac
    done
    
    # 检查Docker环境
    check_docker
    
    # 执行命令
    case $command in
        build)
            build_image
            ;;
        start)
            start_services
            ;;
        stop)
            stop_services
            ;;
        restart)
            restart_services
            ;;
        logs)
            show_logs
            ;;
        init)
            init_database
            ;;
        clean)
            clean_resources "$@"
            ;;
        *)
            log_error "未知命令: $command"
            show_help
            exit 1
            ;;
    esac
}

# 执行主函数
main "$@" 